$(function() {
	var selContext = $('#sel'), queryString = decodeURI(window.location.search
			.substr(1)), differContacts, // 默认展示为普通通讯录
	referrer = matchQueryString(queryString, "referrer"),
	cReg = /\s*"type"\s*:\s*"company"/, // 匹配单位通讯录
	dReg = /\s*"type"\s*:\s*"directory"/, // 匹配本地通讯录
	maxCount = (referrer==='9')?100:9, // 最大参会人数量
	tips=(referrer==='9')?'文字留言最多支持100人':'多方通话最多能添加9人',
	hasAll=false,
	key=matchQueryString(queryString, "key"),
	paging,//是否分页
	comp, // 单位通讯录
	telp, // 手机通讯录
	companyContacts = [], // 单位联系人
	directoryContacts = [], // 通讯录
	caller = localCache.getSessionItem('caller'), // 主叫号码
	callerName = localCache.getSessionItem('callerName'), // 主叫姓名
	search = $('#search').on('input', function() {
		var value = $(this).val();
		loading.css('display', 'none');
		if (value === '') {
			getSelectedDirectory().reload(value, callback);
		} else
			getSelectedDirectory().reset().search(value, callback);
	}), addButton = $('#addContact').on('click', function() {// 添加参与人按钮
		var value = search.val(), validateResult;
		validateResult = validateNumber(value);
		if (!validateResult.success) {
			new UserPrompt(validateResult.msg);
			return;
		}
		if (selCount > maxCount) {
			new UserPrompt(tips);
			return;
		}
		if (contains(value)) {// 号码重复添加
			new UserPrompt('号码' + value + '已经添加，不能重复添加');
			return;
		}
		if (value) {// 校验是否为手机号或座机号
			others.push(value);
			selContext.text(++selCount);
			search.val('');
			getSelectedDirectory().reload('', callback);
		}
	}), create = $('#create').on('click', function() {
		if (selCount > maxCount) {
			new UserPrompt(tips);
			return;
		}
		var rc = [ {
			name : callerName,
			telephone : caller,
			type : 'main'
		} ].concat(comp.getAddedContacts(), otherData());
		if (differContacts)
			rc = rc.concat(telp.getAddedContacts());
		if(referrer==='9'){
			var newkey="sms"+new Date().getTime();
			localCache.setSessionItem(newkey,JSON.stringify({
				data : rc
			}));
			localCache.removeSessionItem(key); 
			router(Number(referrer), '?key=' + newkey, false);
		}else{
			router(Number(referrer), '?data=' + JSON.stringify({
				data : rc
			}), false);
		}
		
	}), others = [], company = {
		data : {},
		size : 0
	}, phone = {
		data : {},
		size : 0
	}, selCount = 0, load = false, loading = $('#loading').css('display',
			'none'), header = $('#header'), title = $('#title').css('display',
			'none');// 已添加参会人数量
	var isLoadContacts = localCache.getSessionItem('isLoadContacts'), loadPrompt;// 是否加载通讯录数据
	$('#count').text(maxCount);
	if (isLoadContacts === '1') {// 需要加载通讯录
		var userContactsObject = localCache.getSessionItem('user_contacts');
		if (userContactsObject !== null && userContactsObject !== '') {// 从缓存中获取到通讯录数据
			loadContacts(JSON.parse(userContactsObject), userContactsObject);
		} else {
			loadPrompt = new LoadPrompt('正在获取通讯录信息，请稍后...');
			/** 接口方法，供isv调用* */
			window.setcontacts = function(contactsObject) {
				if (contactsObject) {
					var co;
					try {
						co = JSON.stringify(contactsObject);
						localCache.setSessionItem('user_contacts', co);// 将用户通讯录缓存
					} catch (err) {
						// 缓存用户通讯录数据异常，暂不处理
					}
					if (!load)
						loadContacts(contactsObject, co);
				}
			}
			/** ios或android捕捉此请求 * */
			createUrl('getcontacts://dudu?app_key='
					+ localCache.getSessionItem('account_identifer'));
			/** 如果通讯录数据长时间未回调，进行超时处理 * */
			setTimeout(function() {
				if (!load)
					loadContacts();
				new UserPrompt('从应用中获取通讯录超时');
			}, 5000);
		}
	} else {// 不需要获取通讯录数据
		loadPrompt = new LoadPrompt('正在加载通讯录信息，请稍后...');
		loadContacts();
	}
	
	$('.all_choose .choose').click(function(){
		if(!hasAll){
			$(this).css('display','none');
			$('.all_choose .no_choose').css('display','block');
			selContext.text(selCount=(getSelectedDirectory().selectAll(function(i,elem,l){
				return i<=(maxCount-l-others.length);
			})+others.length));
			hasAll=true;
		}    
	});
	$('.all_choose .no_choose').click(function(){
		if(hasAll){
			$(this).css('display','none');
			$('.all_choose .choose').css('display','block');
			getSelectedDirectory().unselectAll();
			selContext.text(selCount=others.length);
			hasAll=false;
		}
	});

	function createContacts(context, searchContext, selectedContacts, type,
			contacts) {
		var maxSize = 0;// 默认加载全部通讯录
		if (contacts.length > 100) {// 通讯录记录数量大于100个，采取分页加载
			maxSize = 20;
			utils.lazyload(function() {
				if (!getSelectedDirectory().next(search.val(), callback)) {// 没有查询结果
					loading.css('display', 'block');
				}
			});
		}
		var contact = new Dudu.Directory($(context), type, $(searchContext),
				selectedContacts, {
					caller : caller
				}, maxSize);
		$.each(contacts, function(index, data) {
			contact.addContact(data.name, data.telephone);
		});
		return contact
				.create({
					dial : function(param) {
						location.assign("two_call.html?caller=" + param.caller
								+ "&called=" + param.called + "&calledName="
								+ param.calledName + "&calledType="
								+ param.calledType);
					}
				});
	}

	function containsContacts(contacts, number) {
		if (!contacts || contacts.length === 0)
			return false;
		return contacts.toString().indexOf(number) > -1;
	}

	function loadContacts(userContacts, ucStringify) {
		var contacts = localCache.getSessionItem('contacts'), arrs = [];
		differContacts = localCache.getSessionItem('differContacts');
		if (differContacts) {
			differContacts = Boolean(Number(differContacts));
		} else {
			if (contacts) {
				differContacts = cReg.test(contacts) || dReg.test(contacts);
			}
			if (userContacts && userContacts.length > 0) {
				differContacts = cReg.test(ucStringify)
						|| dReg.test(ucStringify);
			}
			localCache.setSessionItem('differContacts', differContacts ? 1 : 0);
		}

		load = true;
		var _com = [], _dir = [];
		if (contacts) {
			Array.prototype.push.apply(arrs, JSON.parse(contacts));
		}
		if (userContacts && userContacts.length > 0) {
			Array.prototype.push.apply(arrs, userContacts);
		}
		if (differContacts) {
			title.css('display', '');
		} else {
			header.addClass('launch_header');
			header.prepend('通讯录');
		}
		if (arrs.length > 0) {
			$.each(arrs, function(i, data) {
				if(data.telephone!==''){
					if (differContacts) {
						if (data.type === 'company'
								&& _com.join(',').indexOf(data.telephone) == -1) {
							companyContacts.push(data);
							_com.push(data.telephone);
						} else if (data.type === 'directory'
								&& _dir.join(',').indexOf(data.telephone) == -1) {
							directoryContacts.push(data);
							_dir.push(data.telephone);
						}
					} else {
						if( _com.join(',').indexOf(data.telephone) == -1){
							companyContacts.push(data);
							_com.push(data.telephone);
						}
					}
				}
			});
		}

		// 已选择的串
		var search = decodeURI(window.location.search.substr(1)), callees, data;
		if(referrer==='9'){
			data=localCache.getSessionItem(key);
		}else{
			data = matchQueryString(search, 'data');
		}
		if (data) {
			callees = JSON.parse(data).data;
			if (callees && callees.length > 1) {// 存在
				callees = callees.slice(1);
			}
			callees
					&& $
							.each(
									callees,
									function(i, mem) {
										if (differContacts) {
											if (mem.type === 'company'
													|| ((!mem.type || mem.type === '') && _com
															.join(',')
															.indexOf(
																	mem.telephone) > -1)) {
												company.data[mem.telephone] = mem.name;
												company.size++;
											} else if (mem.type === 'directory'
													|| ((!mem.type || mem.type === '') && _dir
															.join(',')
															.indexOf(
																	mem.telephone) > -1)) {
												phone.data[mem.telephone] = mem.name;
												phone.size++;
											} else if (mem.type === 'others'
													|| (!mem.type || mem.type === '')) {
												others.push(mem.telephone);
											}
										} else {
											if (mem.type === 'main')// 主叫不进行判断
												return;
											if (_com.join(',').indexOf(
													mem.telephone) > -1) {
												company.data[mem.telephone] = mem.name;
												company.size++;
											} else {
												others.push(mem.telephone);
											}
										}
									});
			selCount = company.size + phone.size + others.length;
		}
		paging=companyContacts.length>100;
		if(differContacts||paging){//分页或通讯录分开展示时，全选功能屏蔽
			$('.all_choose .choose').css('display','none');
		}
		comp = createContacts('#js-diylist', '#js-diylist-search', company,
				'company', companyContacts).select();
		if (differContacts)
			telp = createContacts('#js-diylisttel', '#js-diylisttel-search',
					phone, 'directory', directoryContacts);
		if (selCount > 0)
			selContext.text(selCount);
		if(!paging&&!differContacts&&(company.size===companyContacts.length||(company.size+others.length===maxCount))){
			$('.all_choose .choose').css('display','none');
			$('.all_choose .no_choose').css('display','block');
			hasAll=true;
		}
		if (loadPrompt) {// 关闭加载页
			loadPrompt.close();
			loadPrompt = null;
		}
	}
	;

	$('#indexback').on('click', function() {
		if(referrer==='9'){  
			var rc = [ {
				name : callerName,
				telephone : caller,
				type : 'main'
			} ].concat(comp.getAddedContacts(), otherData());
			if (differContacts)
				rc = rc.concat(telp.getAddedContacts());
			router(Number(referrer), '?referrer=9&key='+key, true);
		}else{
			router(Number(referrer), window.location.search, true);
		}
	});

	$(document)
			.on(
					'click',
					'#js-diylist div,#js-diylist-search div,#js-diylisttel div,#js-diylisttel-search div',
					function() {
						var elem = $(this);
						var name = elem.attr('name');
						var tel = elem.attr('tel');
						var sel = getSelectedDirectory();
						if (!elem.hasClass('checkboxd')) {
							if (selCount > maxCount) {
								new UserPrompt(tips);
								return;
							}
							if (!contains(tel) && sel.addConference(name, tel)) {
								elem.addClass('checkboxd');
				    			$(this).find('strong').html('&#xe610;');
								selContext.text(++selCount);
								if(!paging&&!differContacts){
									var ctx=sel.getContext();
									if(ctx.find('div').length>maxCount){
										if(ctx.find('div[class="nomail checkboxd"]').length===(maxCount-others.length)){
											$('.all_choose .choose').css('display','none');
											$('.all_choose .no_choose').css('display','block');
											hasAll=true;
										}		
									}else{
										if(ctx.find('div').length===(selCount-others.length)){
											$('.all_choose .choose').css('display','none');
											$('.all_choose .no_choose').css('display','block');
											hasAll=true;
										}	
									}
								}																	
							}
						} else {
							var unSelectedContact = comp.isSelected() ? telp
									: comp;
							if (sel.removeConference(name, tel)
									|| unSelectedContact.removeConference(name,
											tel)) {
								elem.removeClass('checkboxd');
				    			$(this).find('strong').html('&#xe611;');
								selContext.text(--selCount);
								if(!paging&&!differContacts){
									$('.all_choose .no_choose').css('display','none');
									$('.all_choose .choose').css('display','block');
									hasAll=false;
								}								
							}
						}
					});

	function callback(search, result) {
		if ((result && result.length > 0) || search == '') {
			addButton.css('display', 'none');
		} else {
			addButton.css('display', 'block');
		}
		if (differContacts) {
			var unSelectedContact = comp.isSelected() ? telp : comp, selectedContact = getSelectedDirectory();
			var current = this.find('div');
			if (current && current.length > 0) {
				current.each(function(index, element) {
					var context = $(this), tel = context.find('span').html();
					if (unSelectedContact.alreadyAdd(tel)
							&& !selectedContact.alreadyAdd(tel)) {// 关联添加的号码
						context.addClass('checkboxd');
		    			$(this).find('strong').html('&#xe610;');
					}
					if (!selectedContact.alreadyAdd(tel)
							&& !unSelectedContact.alreadyAdd(tel)) {// 删除关联添加失效的号码
						context.removeClass('checkboxd');
		    			$(this).find('strong').html('&#xe611;');
					}
				});
			}
		} else {
			var current = this.find('div');
			if (current && current.length > 0) {
				current.each(function(index, element) {
					var context = $(this), tel = context.find('span').html();
					if (comp.alreadyAdd(tel)) {// 关联添加的号码
						context.addClass('checkboxd');
		    			$(this).find('strong').html('&#xe610;');
					} else{
						context.removeClass('checkboxd');
		    			$(this).find('strong').html('&#xe611;');
					}
				});
			}
		}
	}

	$('.wrap .header_title span').click(function() {
		var target = $(this);
		if (!target.hasClass('current')) {
			target.addClass('current').siblings().removeClass('current');
			if (comp.isSelected()) {
				comp.unselect();
				telp.select(search.val(), callback);
				
			} else {
				telp.unselect();
				comp.select(search.val(), callback);
			}
		}
	});

	function getSelectedDirectory() {
		if (!differContacts)
			return comp;
		if (comp.isSelected()) {
			return comp;
		} else {
			return telp;
		}
	}

	function otherData() {
		var rc = [];
		for (var i = 0; i < others.length; i++) {
			rc.push({
				name : others[i],
				telephone : others[i],
				type : 'others'
			});
		}
		return rc;
	}

	function contains(tel) {
		if(referrer==='9'){
			if (differContacts)
				return comp.alreadyAdd(tel) || telp.alreadyAdd(telp)
						|| (others.join(',').indexOf(tel) > -1);
			else
				return comp.alreadyAdd(tel) || (others.join(',').indexOf(tel) > -1);
		}else{
			if (differContacts)
				return comp.alreadyAdd(tel) || telp.alreadyAdd(telp)
						|| (others.join(',').indexOf(tel) > -1) || caller == tel;
			else
				return comp.alreadyAdd(tel) || (others.join(',').indexOf(tel) > -1)
						|| caller == tel;
		}
	}

})
